package com.ho1ho.audioexample.tcp;

import android.util.Log;

import com.ho1ho.audioexample.MainActivity;
import com.ho1ho.audioexample.utils.AacDecoder;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Created by Michael Leo <y@ho1ho.com><br>
 * Date: 2020/02/05 13:34
 * <p>
 * Code is far away from bug with the animal protecting
 * </p>
 * <pre>
 * ----------Dragon be here!----------/
 *    ┏┓   ┏┓
 *   ┏┛┻━━━┛┻┓
 *   ┃       ┃
 *   ┃   ━   ┃
 *   ┃ ┳┛ ┗┳ ┃
 *   ┃       ┃
 *   ┃   ┻   ┃
 *   ┃       ┃
 *   ┗━┓   ┏━┛
 *     ┃   ┃神兽保佑
 *     ┃   ┃代码无BUG！
 *     ┃   ┗━━━┓
 *     ┃       ┣┓
 *     ┃       ┏┛
 *     ┗┓┓┏━┳┓┏┛
 *      ┃┫┫ ┃┫┫
 *      ┗┻┛ ┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * </pre>
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final String TAG = TcpServerHandler.class.getSimpleName();

    private AacDecoder mDecoder;

    public TcpServerHandler() {
        mDecoder = new AacDecoder(MainActivity.DEFAULT_SAMPLE_RATES,
                MainActivity.CHANNEL_OUT,
                MainActivity.DEFAULT_AUDIO_FORMAT,
                MainActivity.AUDIO_CSD_0);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//        mIsPlaying = true;
        ByteBuf bb = (ByteBuf) msg;
//        int dataLen = bb.readInt();
//        byte[] audioData = new byte[dataLen];
//        bb.readBytes(audioData);

        byte[] audioData = ByteBufUtil.getBytes(bb);

//        Log.w(TAG, "Received audio data[" + audioData.length + "]: " + Arrays.toString(audioData));

        if ("START-AUDIO".equals(new String(audioData, StandardCharsets.UTF_8))) {
            Log.e(TAG, "START-AUDIO");
            mDecoder.initOutputStream();
            return;
        }

        try {
            mDecoder.writeDataToDisk(audioData);
            mDecoder.decodeAndPlay(audioData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Play pcm data directly.
//        mAudioTrack.write(data, 0, data.length);

//        ctx.channel().writeAndFlush("server accepted msg: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Log.w(TAG, "exceptionCaught!", cause);
        ctx.close();
    }

}